package com.foreknow.service.Impl;

import com.foreknow.dao.CartDao;
import com.foreknow.dao.impl.CartDaoImpl;
import com.foreknow.po.Cart;
import com.foreknow.service.CartService;
import com.foreknow.util.DBUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {

    @Override
    public List<Cart> listCart(String userId, Integer businessId) {
        CartDao dao = new CartDaoImpl();
        List<Cart> list = new ArrayList<>();
        try {
             list = dao.listCart(userId,businessId);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public Integer saveCart(String userId, int foodId, int businessId) {
        CartDao dao = new CartDaoImpl();
        int result = 0;
        try {
            DBUtil.beginTransaction();
            result = dao.saveCart(userId,foodId,businessId);
            DBUtil.commitTransaction();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public Integer updateCart(String userId, int foodId, int businessId, int quantity) {
        CartDao dao = new CartDaoImpl();
        int result = 0;

        try {
            DBUtil.beginTransaction();
            result = dao.updateCart(userId,foodId,businessId,quantity);
            DBUtil.commitTransaction();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }

        return result;
    }

    @Override
    public Integer removeCart(String userId, Integer foodId, Integer businessId) {
        CartDao dao = new CartDaoImpl();
        int result = 0;
        try {
            DBUtil.beginTransaction();
            result = dao.removeCart(userId,foodId,businessId);
            DBUtil.commitTransaction();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }

        return result;
    }
}
